<!-- src/views/BatchImportView.vue -->
<template>
  <div class="batch-import-view">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>📚 批量导入图书</h2>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </el-header>
      <el-main>
        <el-card>
          <el-alert
            title="导入说明"
            type="info"
            description="请下载模板文件，按照格式填写后上传。支持.xlsx格式文件。"
            show-icon
            style="margin-bottom: 20px;"
          />

          <el-button
            type="primary"
            size="small"
            @click="downloadTemplate"
            icon="Download"
            style="margin-bottom: 20px;"
          >
            下载模板
          </el-button>

          <el-upload
            ref="uploadRef"
            drag
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            accept=".xlsx,.xls"
            :limit="1"
            :on-exceed="handleExceed"
            style="margin-bottom: 30px;"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传xlsx/xls文件，且不超过10MB
              </div>
            </template>
          </el-upload>

          <!-- 预览表格 -->
          <div v-if="previewData.length > 0" class="preview-section">
            <div class="preview-header">
              <h4>数据预览 ({{ previewData.length }} 条)</h4>
              <div class="preview-stats">
                <el-tag type="success" size="small">有效: {{ validCount }}</el-tag>
                <el-tag type="danger" size="small" style="margin-left: 8px;">无效: {{ invalidCount }}</el-tag>
              </div>
            </div>

            <el-table
              :data="previewData"
              height="400"
              style="width: 100%"
              size="small"
              border
            >
              <el-table-column prop="rowIndex" label="行号" width="60" align="center" />
              <el-table-column prop="isbn" label="ISBN" width="180" show-overflow-tooltip />
              <el-table-column prop="title" label="书名" min-width="200" show-overflow-tooltip />
              <el-table-column prop="author" label="作者" width="120" show-overflow-tooltip />
              <el-table-column prop="genre" label="分类" width="100" align="center" />
              <el-table-column prop="publicationDate" label="出版日期" width="120" align="center" />
              <el-table-column prop="totalCopies" label="总数量" width="80" align="center" />
              <el-table-column label="状态" width="100" align="center">
                <template #default="scope">
                  <el-tooltip
                    v-if="!scope.row.valid"
                    :content="scope.row.errors.join(', ')"
                    placement="top"
                  >
                    <el-tag type="danger" size="small" style="cursor: help;">
                      无效
                    </el-tag>
                  </el-tooltip>
                  <el-tag
                    v-else
                    type="success"
                    size="small"
                  >
                    有效
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 导入按钮 -->
          <div v-if="previewData.length > 0" class="import-actions">
            <el-button
              type="primary"
              @click="handleImport"
              :loading="importing"
              :disabled="validCount === 0"
              size="large"
            >
              确认导入 {{ validCount }} 条有效数据
            </el-button>
            <el-button @click="clearPreview" size="large">
              重新上传
            </el-button>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as XLSX from 'xlsx'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Download } from '@element-plus/icons-vue'
import { saveAs } from 'file-saver'
import api from '@/services/api'

export default {
  name: 'BatchImportView',
  components: {
    UploadFilled,
    // eslint-disable-next-line vue/no-unused-components
    Download
  },
  setup() {
    const router = useRouter()
    const uploadRef = ref(null)
    const fileList = ref([])
    const previewData = ref([])
    const importing = ref(false)

    const validCount = computed(() => {
      return previewData.value.filter(item => item.valid).length
    })

    const invalidCount = computed(() => {
      return previewData.value.filter(item => !item.valid).length
    })

    const goBack = () => {
      router.push('/books')
    }

    const downloadTemplate = () => {
      const templateData = [
        {
          ISBN: '978-0-123456-78-9',
          书名: 'Spring Boot实战',
          作者: '张三',
          分类: '编程',
          出版日期: '2023-01-15',
          总数量: 5
        },
        {
          ISBN: '978-0-987654-32-1',
          书名: 'Vue.js从入门到精通',
          作者: '李四',
          分类: '编程',
          出版日期: '2022-11-20',
          总数量: 3
        },
        {
          ISBN: '978-1-111111-11-1',
          书名: '百年孤独',
          作者: '加西亚·马尔克斯',
          分类: '文学',
          出版日期: '2020-05-10',
          总数量: 10
        }
      ]

      const ws = XLSX.utils.json_to_sheet(templateData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '图书模板')

      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([wbout], { type: 'application/octet-stream' })
      saveAs(blob, '图书导入模板.xlsx')

      ElMessage.success('模板下载成功！')
    }

    const validateRow = (row) => {
      const errors = []

      if (!row.isbn || row.isbn.toString().trim() === '') {
        errors.push('ISBN不能为空')
      } else if (row.isbn.toString().length < 10 || row.isbn.toString().length > 20) {
        errors.push('ISBN长度应在10-20字符之间')
      }

      if (!row.title || row.title.toString().trim() === '') {
        errors.push('书名不能为空')
      } else if (row.title.toString().length > 100) {
        errors.push('书名长度不能超过100字符')
      }

      if (!row.author || row.author.toString().trim() === '') {
        errors.push('作者不能为空')
      } else if (row.author.toString().length > 50) {
        errors.push('作者名长度不能超过50字符')
      }

      const validGenres = ['文学', '小说', '编程', '历史', '科学', '艺术', '其他']
      if (!row.genre || !validGenres.includes(row.genre.toString().trim())) {
        errors.push('分类必须是: ' + validGenres.join(', '))
      }

      if (!row.publicationDate) {
        errors.push('出版日期不能为空')
      } else {
        let dateStr = row.publicationDate
        if (typeof dateStr === 'object' && dateStr instanceof Date) {
          dateStr = dateStr.toISOString().split('T')[0]
        } else if (typeof dateStr === 'number') {
          const date = new Date(Math.round((dateStr - 25569) * 86400 * 1000))
          dateStr = date.toISOString().split('T')[0]
        } else {
          dateStr = dateStr.toString().trim()
          if (dateStr.includes('/')) {
            const parts = dateStr.split('/')
            if (parts.length === 3) {
              if (parts[0].length <= 2 && parts[1].length <= 2) {
                dateStr = `${parts[2]}-${parts[0].padStart(2, '0')}-${parts[1].padStart(2, '0')}`
              }
            }
          }
        }

        const date = new Date(dateStr)
        if (isNaN(date.getTime())) {
          errors.push('出版日期格式无效')
        } else if (date > new Date()) {
          errors.push('出版日期不能是未来日期')
        }
        row.publicationDate = dateStr
      }

      let totalCopies = row.totalCopies
      if (typeof totalCopies === 'string') {
        totalCopies = parseInt(totalCopies.trim())
      }

      if (totalCopies === undefined || totalCopies === null || isNaN(totalCopies)) {
        errors.push('总数量不能为空且必须是数字')
      } else if (totalCopies < 1 || totalCopies > 1000) {
        errors.push('总数量必须是1-1000之间的数字')
      }

      row.totalCopies = totalCopies

      return {
        valid: errors.length === 0,
        errors: errors
      }
    }

    const handleFileChange = (file) => {
      console.log('文件已选择:', file)

      previewData.value = []

      if (file.size > 10 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过10MB')
        uploadRef.value.clearFiles()
        return
      }

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })

          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]

          const jsonData = XLSX.utils.sheet_to_json(worksheet, {
            header: 1,
            raw: true
          })

          if (jsonData.length === 0) {
            ElMessage.error('Excel文件为空')
            return
          }

          const headers = jsonData[0].map(h => h.toString().trim())
          console.log('Excel表头:', headers)

          const expectedHeaders = ['ISBN', '书名', '作者', '分类', '出版日期', '总数量']
          const headerMap = {}

          expectedHeaders.forEach(expectedHeader => {
            const index = headers.findIndex(h => h === expectedHeader)
            if (index !== -1) {
              headerMap[expectedHeader] = index
            }
          })

          if (Object.keys(headerMap).length !== expectedHeaders.length) {
            const missingHeaders = expectedHeaders.filter(h => !(h in headerMap))
            ElMessage.error(`Excel文件缺少必要列: ${missingHeaders.join(', ')}`)
            return
          }

          const parsedData = []
          for (let i = 1; i < jsonData.length; i++) {
            const row = jsonData[i]
            if (!row || row.length === 0 || (row.length === 1 && !row[0])) {
              continue
            }

            const bookData = {
              isbn: row[headerMap['ISBN']],
              title: row[headerMap['书名']],
              author: row[headerMap['作者']],
              genre: row[headerMap['分类']],
              publicationDate: row[headerMap['出版日期']],
              totalCopies: row[headerMap['总数量']]
            }

            const validation = validateRow(bookData)
            parsedData.push({
              rowIndex: i + 1,
              ...bookData,
              valid: validation.valid,
              errors: validation.errors
            })
          }

          previewData.value = parsedData
          console.log('解析完成的数据:', parsedData)

          if (parsedData.length === 0) {
            ElMessage.warning('未找到有效数据行')
          } else {
            ElMessage.success(`成功解析 ${parsedData.length} 条数据`)
          }

        } catch (error) {
          console.error('解析Excel文件失败:', error)
          ElMessage.error('解析Excel文件失败，请检查文件格式')
        }
      }

      reader.onerror = (error) => {
        console.error('文件读取失败:', error)
        ElMessage.error('文件读取失败')
      }

      reader.readAsArrayBuffer(file.raw)
    }

    const handleFileRemove = () => {
      previewData.value = []
    }

    const handleExceed = () => {
      ElMessage.warning('只能上传一个文件')
    }

    const clearPreview = () => {
      previewData.value = []
      uploadRef.value.clearFiles()
    }

    const handleImport = async () => {
      try {
        if (validCount.value === 0) {
          ElMessage.warning('没有有效的数据可以导入')
          return
        }

        await ElMessageBox.confirm(
          `确认导入 ${validCount.value} 条有效数据吗？`,
          '导入确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        importing.value = true

        const validData = previewData.value.filter(item => item.valid)
        const requestData = {
          books: validData.map(book => ({
            isbn: book.isbn.toString(),
            title: book.title.toString(),
            author: book.author.toString(),
            genre: book.genre.toString(),
            publicationDate: book.publicationDate,
            totalCopies: book.totalCopies
          }))
        }

        // 调用后端API
        const response = await api.post('/api/v1/books/batch-import', requestData)

        ElMessage.success(`批量导入成功！成功导入 ${response.successCount} 条数据`)
        router.push('/books')

      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量导入失败:', error)
          let errorMessage = '批量导入失败'
          if (error.response && error.response.message) {
            errorMessage = error.response.message
          } else if (error.message) {
            errorMessage = error.message
          }
          ElMessage.error(errorMessage)
        }
      } finally {
        importing.value = false
      }
    }

    return {
      uploadRef,
      fileList,
      previewData,
      importing,
      validCount,
      invalidCount,
      goBack,
      downloadTemplate,
      handleFileChange,
      handleFileRemove,
      handleExceed,
      clearPreview,
      handleImport
    }
  }
}
</script>

<style scoped>
.batch-import-view {
  height: 100vh;
}
.el-header {
  background-color: #f5f7fa;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}
.el-main {
  padding: 20px;
}
.preview-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.preview-stats {
  display: flex;
  gap: 8px;
}
.import-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>